var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'sell/ecoupon/temp';

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var codes = [];
					var names = [];
					for(var i=0;i<selected.length;i++){
						codes.push(selected[i].sp_code);
						names.push(selected[i].sp_name);
					}
					$("#shop_codes").val(codes.join(","));
					$("#shop_names").val(names.join(","));
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#ec_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	doQueryBrand : function(code,name){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var codes = [];
					var names = [];
					for(var i=0;i<selected.length;i++){
						codes.push(selected[i].bd_code);
						names.push(selected[i].bd_name);
					}
					$("#"+code).val(codes.join(","));
					$("#"+name).text(names.join(","));
				}
			},
			cancel:true
		});
	},
	doQueryType : function(code,name){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 280,
		   	height : 320,
		   	top : 50,
		   	left : 250,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : '请选择商品类别!'});
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var codes = [];
					var names = [];
					for(var i=0;i<selected.length;i++){
						codes.push(selected[i].tp_code);
						names.push(selected[i].tp_name);
					}
					$("#"+code).val(codes.join(","));
					$("#"+name).text(names.join(","));
				}
			},
			cancel:true
		});
	},
	doQueryProduct : function(code,name){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					var codes = [];
					var names = [];
					for(var i=0;i<selected.length;i++){
						codes.push(selected[i].pd_code);
						names.push(selected[i].pd_name);
					}
					$("#"+code).val(codes.join(","));
					$("#"+name).text(names.join(","));
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate_temp : function(oper, id){
		var height = 260;
		var width = 390;
		var ec_type = $("#ec_type").val();
		if(oper == 'add'){
			title = '新增';
			url = config.BASEPATH+"sell/ecoupon/to_temp_add/"+ec_type;
			data = {oper: oper, callback: this.callback_temp};
		}else if(oper == 'edit'){
			title = '修改';
			url = config.BASEPATH+"sell/ecoupon/to_temp_update/"+ec_type+"?ecl_id="+id;
			data = {oper: oper,callback: this.callback_temp};
		}else{
			return false;
		}
		$.dialog({
			title : title,
			content : 'url:'+url,
			data: data,
			width : width,
			height : height,
			max : false,
			min : false,
			cache : false,
			lock: true
		});
	},
	callback_temp: function(data, oper, dialogWin){
		var gridData = $("#grid").data('gridData');
		if(!gridData){
			gridData = {};
			$("#grid").data('gridData', gridData);
		}
		gridData[data.id] = data;
		if(oper == "edit") {
			data.ecl_limitmoney_f = '';
			data.ecl_money_f = '';
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		} 
		if(oper == "add"){
			$("#grid").jqGrid('addRowData', data.id, data, 'first');
			dialogWin && dialogWin.api.close();
		}
	},
	temp_del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'sell/ecoupon/temp_del',
					data:{"ecl_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
							var ids = $("#grid").getDataIDs();
							if(ids.length == 0){
								THISPAGE.addEmptyData();
							}
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
	save:function(){
		if (!$("#form1").valid()) {
			return;
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		if (ids.length <= 1){
			Public.tips({type: 2, content : '方案明细不存在，请补充完整！'});
			return;
		}
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"sell/ecoupon/save",
			data:$('#form1').serialize(),
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : data.message});
					handle.loadData(data.data);
					setTimeout("api.zindex()",500);
				}else{
					Public.tips({type: 1, content : data.message});
					setTimeout("api.zindex()",500);
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.ec_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="增加">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	},
	formatLimitMoney :function(val, opt, row){
		return $.trim(row.ecl_limitmoney);
	},
	formatMoney :function(val, opt, row){
		return $.trim(row.ecl_money);
	}
};

function modeClick(obj){
	var mode = $(obj).val();
	$("#mode_codes").val("");
	$("#mode_names").text("");
	if(mode == 1){
		$("#mode_code_td").hide();
	}else if(mode == 2){
		$("#mode_label").text("所选品牌：");
		Utils.doQueryBrand("mode_codes", "mode_names")
	}else if(mode == 3){
		$("#mode_label").text("所选类别：");
		Utils.doQueryType("mode_codes", "mode_names");
	}else if(mode == 4){
		$("#mode_label").text("所选商品：");
		Utils.doQueryProduct("mode_codes", "mode_names");
	}
}

function usemodeClick(obj){
	var mode = $(obj).val();
	$("#use_mode_codes").val("");
	$("#use_mode_names").text("");
	if(mode == 1){
		$("#use_mode_code_td").hide();
	}else if(mode == 2){
		$("#use_mode_label").text("所选品牌：");
		Utils.doQueryBrand("use_mode_codes", "use_mode_names")
	}else if(mode == 3){
		$("#use_mode_label").text("所选类别：");
		Utils.doQueryType("use_mode_codes", "use_mode_names");
	}else if(mode == 4){
		$("#use_mode_label").text("所选商品：");
		Utils.doQueryProduct("use_mode_codes", "use_mode_names");
	}
}

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		this.initLevelCombo();
		this.$_mode = $("#modeTd").cssRadio({ callback: function($_obj){
			$("#ec_mode").val($_obj.find("input").val());
		}});
		this.$_use_mode = $("#use_modeTd").cssRadio({ callback: function($_obj){
			$("#ec_use_mode").val($_obj.find("input").val());
		}});
	},
	initLevelCombo : function(){//1.最高2.较高3.一般4.较低5.最低
		var data = [ 
	                {Code : '1',Name : '最高'}, 
	                {Code : '2',Name : '较高'},
	                {Code : '3',Name : '一般'},
	                {Code : '4',Name : '较低'},
	                {Code : '5',Name : '最低'},
	              ];
		$('#span_level').combo({
			value : 'Code',
			text : 'Name',
			width : 132,
			height : 80,
			listId : '',
			defaultSelected : 0,
			editable : false,
			callback : {
				onChange : function(data) {
					$("#ec_level").val(data.Code);
				}
			}
		}).getCombo().loadData(data);
		var pdata = [{id:"0",name:"线上领取"},
		             {id:"1",name:"收银发放"}
		             ]
		$('#spanType').combo({
			data:pdata,
			value : 'id',
			text : 'name',
			width : 132,
			height : 80,
			listId : '',
			defaultSelected : 0,
			editable : false,
			callback : {
				onChange : function(data) {
					if(data.id == 1){
						$("#modeTr").show();
						$('#grid').showCol("ecl_usedmoney").showCol("ecl_money").showCol("ecl_limitmoney")
								.hideCol("ecl_limitmoney_f").hideCol("ecl_money_f").hideCol("ecl_amount");
					}else{
						$("#modeTr").hide();
						$('#grid').hideCol("ecl_usedmoney").hideCol("ecl_money").hideCol("ecl_limitmoney")
								.showCol("ecl_limitmoney_f").showCol("ecl_money_f").showCol("ecl_amount");
					}
					$("#ec_type").val(data.id);
				}
			}
		}).getCombo();
	},
	addEmptyData:function(){
    	var emptyData = {};
    	$("#grid").addRowData(0, emptyData);
    },
	initGrid:function(){
		var _height = $(parent).height()-337,_width = $(parent).width()-3;
		var colModel = [
		    {label:'操作',name:'operate', width: 60, fixed:true, formatter: handle.operFmatter, sortable:false},
	    	{label:'满多少元',name: 'ecl_usedmoney', index: 'ecl_usedmoney', width: 100,hidden:true},
	    	{label:'赠送',name: 'ecl_money', index: 'ecl_money', width: 100,hidden:true},
	    	{label:'满多少元可使用',name: 'ecl_limitmoney', index: 'ecl_limitmoney', width: 100,align:'right',hidden:true},
	    	{label:'满多少元',name: 'ecl_limitmoney_f', index: 'ecl_limitmoney', width: 100,align:'right',formatter: handle.formatLimitMoney},
	    	{label:'减多少',name: 'ecl_money_f', index: 'ecl_money', width: 100,align:'right',formatter: handle.formatMoney},
	    	{label:'发放数量',name: 'ecl_amount', index: 'ecl_amount', width: 100,align:'right'},
	    	{label:'备注',name: 'ecl_remark', index: 'ecl_remark', width: 180,align:'center'}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:-1,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'ecl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").getDataIDs();
				if(ids.length == 0){
					THISPAGE.addEmptyData();
				}
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(){
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-plus', function (e) {
			e.preventDefault();
			handle.operate_temp('add');
		});
		$('#grid').on('click', '.operating .ui-icon-pencil', function (e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			if(id == 0){
				return;
			}
			handle.operate_temp('edit', id);
		});
		//删除
		$('#grid').on('click', '.operating .ui-icon-trash', function(e){
			e.preventDefault();
			var id = $(this).parent().data('id');
			if(id == 0){
				return;
			}
			handle.temp_del(id);
		});
	}
};
THISPAGE.init();